package com.app.scale.record;

import android.graphics.Bitmap;
import android.text.TextUtils;

import com.app.scale.basis.BasisActivity;
import com.app.scale.basis.Constants;
import com.app.scale.bean.BasisBean;
import com.app.scale.bean.GoodsListBean;
import com.app.scale.bean.GoodsListData;
import com.app.scale.bean.LoginBean;
import com.app.scale.bean.RecordListData;
import com.app.scale.bean.SupplierListData;
import com.app.scale.bean.UserInfoBean;
import com.app.scale.scale.ScaleActivity;
import com.app.scale.util.UnitUtil;
import com.caysn.autoreplyprint.AutoReplyPrint;
import com.google.gson.Gson;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.LongByReference;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.vandin.weigher.sdk.connector.IWeigh;
import com.vandin.weigher.sdk.connector.IWeighCallback;
import com.vandin.weigher.sdk.connector.WeightData;
import com.vandin.weigher.sdk.weigher.WeightSerialPort;

import java.math.BigDecimal;

import my.DialogUtils;
import my.LogUtil;
import my.MathUtils;
import my.MySharedPreferences;
import my.SystemParamsUtils;
import my.TimeUtils;
import my.http.MyHttpListener;
import my.http.MyHttpUtils;
import my.http.MyParams;

public class RecordPresenterImpl implements RecordPresenter, IWeighCallback {

    BasisActivity activity;
    RecordView recordView;
    private Pointer h = Pointer.NULL;

    MySharedPreferences mSp;
    private IWeigh iWeigh;
    String oldWeight="0";
    String scaleWeight="0";  //真实的秤重量

    public RecordPresenterImpl(BasisActivity activity,RecordView recordView){
        this.recordView = recordView;
        this.activity = activity;
    }

    @Override
    public void getIWeigh() {
        if(mSp == null){
            mSp = new MySharedPreferences(activity);
        }
        if (iWeigh != null) {
            iWeigh.disconnect();
        }
        WeightData weightData = new WeightData();
        weightData.setPort(mSp.getPort());
        weightData.setBaudrate(mSp.getBaudrate());
        iWeigh = new WeightSerialPort(activity, this, weightData);
        iWeigh.OpenScaleUart();
    }

    @Override
    public String getScaleWeight() {
        return scaleWeight;
    }

    @Override
    public void closeIWeigh() {
        if (iWeigh != null) {
            iWeigh.StopRead();
            iWeigh.disconnect();
            iWeigh = null;
        }
    }


    int i = 0;
    @Override
    public void toChange(RecordListData recordListData, GoodsListBean goodsListBean) {
        MyParams params = new MyParams();
        activity.showProgress();
        Gson gson = new Gson();
        i = 0;

        for (GoodsListData data : goodsListBean.getList()){
            String a = gson.toJson(data);
            params.putJson(a);

            MyHttpUtils.postJson(Constants.URL_LEAF_UPDATE_BY_ID, params, new MyHttpListener() {
                @Override
                public void onSuccess(int httpWhat, Object result) {
                    if(activity.isFinishing())return;
                    BasisBean basisBean = (BasisBean) result;
                    i ++;
                    if(i==goodsListBean.getList().size()){
                        activity.dismissProgress();
                        recordView.httpSuccess();
                    }

                }

                @Override
                public void onFailure(int httpWhat, Object result) {
                    if(activity.isFinishing())return;
//                super.onFailure(httpWhat, result);
                    if(result != null &&   !TextUtils.isEmpty(((BasisBean) result).getStatusInfo())){
                        DialogUtils.showErrorDialog(activity,((BasisBean) result).getStatusInfo());
                    }else {
                        DialogUtils.showErrorDialog(activity,"异常！");
                    }
                }

                @Override
                public void onFinish(int httpWhat) {
                    if(activity.isFinishing())return;
                    activity.dismissProgress();
                }
            }, 0, BasisBean.class);
        }
    }

    @Override
    public void toPrint( RecordListData recordListData, GoodsListBean goodsListBean) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                if(goodsListBean == null || goodsListBean.getList().size()<1){
                    recordView.printMessage("无交易记录");
                    return;
                }

                Test_Pos_SampleTicket_58MM_1(recordListData,goodsListBean);
                recordView.printFinish();
            }
        }).start();
    }


    private void Test_Pos_SampleTicket_58MM_1( RecordListData recordListData, GoodsListBean goodsListBean ) {
        Pointer h = OpenPort();
        if (h != Pointer.NULL) {

            AutoReplyPrint.INSTANCE.CP_Pos_ResetPrinter(h);
            AutoReplyPrint.INSTANCE.CP_Pos_SetMultiByteMode(h);
            AutoReplyPrint.INSTANCE.CP_Pos_SetMultiByteEncoding(h, AutoReplyPrint.CP_MultiByteEncoding_UTF8);


            AutoReplyPrint.INSTANCE.CP_Pos_SetAlignment(h, AutoReplyPrint.CP_Pos_Alignment_HCenter);
            AutoReplyPrint.INSTANCE.CP_Pos_SetTextScale(h, 1, 0);
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, ""+ LoginBean.getInstance().getBname()+"收购凭证\r\n");
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "    \r\n");
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "————————————————\n");
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "    \r\n");

            AutoReplyPrint.INSTANCE.CP_Pos_SetAlignment(h, AutoReplyPrint.CP_Pos_Alignment_Left);
            AutoReplyPrint.INSTANCE.CP_Pos_SetTextScale(h, 0, 0);
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "秤编号:  "+ SystemParamsUtils.getAndroidID(activity)+"\n");
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "凭证号:  "+recordListData.getTid()+"\n");
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "日期:  "+ recordListData.getTdt()+"\n");
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "供应商:  "+ recordListData.getCna()+"\n");
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "身份证:  "+ recordListData.getCht()+"\n");
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "--------------------------------\n");


            for (int i= 0;i<goodsListBean.getList().size();i++){
                GoodsListData goodsData =goodsListBean.getList().get(i);
                AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "品名:  "+ goodsData.getGna()+"\n");
                AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "累计净重:  "+ goodsData.getGwt()+"斤"+"\n");
                AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "去皮:  "+ goodsData.getPwt()+"斤"+"\n");
                AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "单价:  "+ goodsData.getGpr()+"元"+"\n");
                AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "金额:  "+ MathUtils.multiply(goodsData.getGwt(),goodsData.getGpr())+"元"+"\n");
                AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "累计:  "+ goodsData.getAcc()+"\n");
                AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "--------------------------------\n");
            }

            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "金额合计:  "+ goodsListBean.getAllSje()+"元"+"\n");
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "重量合计:  "+ goodsListBean.getAllWeight()+"斤"+"\n");

//                    AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "银针溯源余量:  "+ recordListData.getTra1()+"\n");
//                    AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "牡丹溯源余量:  "+ recordListData.getTra2()+"\n");
//                    AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "寿眉溯源余量:  "+ recordListData.getTra3()+"\n");
            }
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "称重员:"+ LoginBean.getInstance().getUname()+"   计价员 :"+ recordListData.getJna()+"\n");

            AutoReplyPrint.INSTANCE.CP_Pos_Beep(h, 1, 500);
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "    \r\n");
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "    \r\n");

        if(!TextUtils.isEmpty(recordListData.getAutoBno())){
            Bitmap bitmap = CodeUtils.createImage(recordListData.getAutoBno(), 150, 150, null);
            AutoReplyPrint.CP_Pos_PrintRasterImageFromData_Helper.PrintRasterImageFromBitmap(h, bitmap.getWidth(), bitmap.getHeight(), bitmap, AutoReplyPrint.CP_ImageBinarizationMethod_Thresholding, AutoReplyPrint.CP_ImageCompressionMethod_None);
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "    \r\n");
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "    \r\n");
        }


        AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "    \r\n");
        AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "    \r\n");

            QueryPrintResult(h);
            AutoReplyPrint.INSTANCE.CP_Port_Close(h);
        }





    private Pointer OpenPort() {
        Pointer h = Pointer.NULL;
        h = AutoReplyPrint.INSTANCE.CP_Port_OpenUsb("VID:0x4B43,PID:0x3538", 1);

        if (h == Pointer.NULL) {
            recordView.printMessage("OpenPort Failed");
        }
        return h;
    }

    @Override
    public void ClosePort() {
        if (h != Pointer.NULL) {
            AutoReplyPrint.INSTANCE.CP_Port_Close(h);
            h = Pointer.NULL;
        }
    }



    private boolean QueryPrintResult(Pointer h) {
        boolean result = AutoReplyPrint.INSTANCE.CP_Pos_QueryPrintResult(h, 30000);
//        recordView.printMessage(result ? "Print Success" : "Print Failed");
        recordView.printMessage(result ? "打印成功" : "打印失败");
        if (!result) {
            LongByReference printer_error_status = new LongByReference();
            LongByReference printer__info_status = new LongByReference();
            LongByReference timestamp_ms_printer_status = new LongByReference();
            if (AutoReplyPrint.INSTANCE.CP_Printer_GetPrinterStatusInfo(h, printer_error_status, printer__info_status, timestamp_ms_printer_status)) {
                AutoReplyPrint.CP_PrinterStatus status = new AutoReplyPrint.CP_PrinterStatus(printer_error_status.getValue(), printer__info_status.getValue());
                String error_status_string = String.format("Printer Error Status: 0x%04X", printer_error_status.getValue() & 0xffff);
                if (status.ERROR_OCCURED()) {
                    if (status.ERROR_CUTTER())
                        error_status_string += "[ERROR_CUTTER]";
                    if (status.ERROR_FLASH())
                        error_status_string += "[ERROR_FLASH]";
                    if (status.ERROR_NOPAPER())
                        error_status_string += "[ERROR_NOPAPER]";
                    if (status.ERROR_VOLTAGE())
                        error_status_string += "[ERROR_VOLTAGE]";
                    if (status.ERROR_MARKER())
                        error_status_string += "[ERROR_MARKER]";
                    if (status.ERROR_ENGINE())
                        error_status_string += "[ERROR_ENGINE]";
                    if (status.ERROR_OVERHEAT())
                        error_status_string += "[ERROR_OVERHEAT]";
                    if (status.ERROR_COVERUP())
                        error_status_string += "[ERROR_COVERUP]";
                    if (status.ERROR_MOTOR())
                        error_status_string += "[ERROR_MOTOR]";
                }
                recordView.printMessage(error_status_string);
            } else {
                recordView.printMessage("CP_Printer_GetPrinterStatusInfo Failed");
            }
        }
        return result;
    }

    @Override
    public void onConnect(int status, String s, boolean b) {
        /**
         * status =1 ; str =正在连接……  ; b = true
         * status =2 ; str =连接成功    ; b = true
         * status =7 ; str =暂停读取    ; b = false
         * status =4 ; str =断开成功    ; b = true
         * status =10 ; str =读取重量    ; b = false           IControl.GetWeight();调用就会回调这个
         */
        switch (status){
            case 2:
                iWeigh.GetWeight();
                break;
        }
    }

    @Override
    public void onReceiveData(String frame, String weight, boolean isSta) {
        //weight的格式 ====      +   0.515

        if(weight.contains("-")){
            recordView.showWeight("0");
            scaleWeight = "0";
            return;
        }
        if(oldWeight.equals(weight)){
            return;
        }else {
            oldWeight = weight;
        }

        try {
//            a = a.substring(0,(a.indexOf(".")+2));
            BigDecimal bd   =  new BigDecimal(MathUtils.multiply(UnitUtil.getNumByString(weight),"2"));
            bd   =   bd.setScale(1,BigDecimal.ROUND_HALF_UP);
            recordView.showWeight(bd.toString());
            scaleWeight = bd.toString();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }
}
